layui.use(['table','form', 'element'], function () {
    let table = layui.table,
        form = layui.form,
        $ = layui.jquery,
       element = layui.element;

    //方法级渲染
    table.render({
        elem: '#admProjectAutoConfig'
        , url: '/admProjectAutoConfig/page'
        , toolbar: '#toolbarTable'
        , title: '自动更新配置'
        , totalRow: true
        ,skin: 'line'
        , where: {
            projectId: $("#projectId").val(),
            namespaceId: $("#namespaceId").val(),
            content: $("#content").val(),
        }
        , id: "admProjectAutoConfig"
        , cols: [[
            {checkbox: true, fixed: true}
            , {field: 'projectName', title: '项目名称', width: 200, sort: true}
            , {field: 'gitlabProjectName', title: 'git项目名', width: 200, sort: true}
            , {field: 'namespaceName', title: '命名空间', width: 200, sort: true}
            , {field: 'branch', title: '分支名称', width: 200, sort: true}
            , {field: 'state', title: '状态', width: 150, sort: true,templet: function (d) {
                    let className = 'layui-bg-red';
                    if (d.state == '1'){
                        className = 'layui-bg-green'
                    }else if (d.state == '2') {
                        className = 'layui-bg-blue'
                    }
                    return '<span class = "layui-badge '+className+'" >'+d.stateName+'</span>';
                }}
            , {field: 'updateTime', title: '更新时间', width: 200, sort: true}
            , {fixed: 'right', title: '操作', toolbar: '#barDemo', width: 200}
        ]]
        , even: true
        , page: true //是否显示分页
        , skip: true //开启跳页
        , limits: [10, 30, 60]
        , width: 1700
        // , height: 'full-150'
        , limit: 10 //每页默认显示的数量
        , parseData: function (res) { //res 即为原始返回的数据
            var data = res.data;
            return {
                "code": status, //解析接口状态   （好像必须是0 才可以）
                "msg": data.desc, //解析提示文本
                "count": data.total, //解析数据长度
                "data": data.records //解析数据列表
            };
        }
        ,done:function (res,currentCount) {
            //***重点***：table渲染完成后渲染element进度条
            element.render()
        }

    });


    //头工具栏事件
    table.on('toolbar(admProjectAutoConfig)', function (obj) {
        let data = table.checkStatus(obj.config.id).data;
        let ids;switch (obj.event) {
            case 'add':
                add();
                break;
            case 'del':
                ids = check(data);
                if (!ids){
                    return
                }
                del(ids);
                break;
            case 'manualTrigger':
                if (data.length!=1){
                    layer.msg("请先勾选1条数据",{icon:2,time:3000});
                    return;
                }
                ids = data[0].id
                manualTrigger(ids);
                break;
        }
        ;
    });

    function check(data) {
        if (data.length==0){
            layer.msg("请先勾选数据",{icon:2,time:3000});
            return;
        }
        let ids = "";
        for (let i = 0; i < data.length; i++) {
            ids+=data[i].id+","
        }
        ids = ids.substr(0,ids.length-1);
        return ids;
    }
    //监听行工具事件
    table.on('tool(admProjectAutoConfig)', function (obj) {
        const data = obj.data;
        if (obj.event === 'update'){
            update(data);
        }else if (obj.event === 'del'){
            del(data.id)
        }
    });

    function del(ids) {
        layer.confirm("确认要删除吗，删除后不能恢复", { title: "删除确认" }, function (index) {
            $.ajax({
                type: "delete",//方法类型
                dataType: "json",//预期服务器返回的数据类型
                url: "/admProjectAutoConfig/"+ids,//url
                success: function (result) {
                    if (result.code == 0) {
                        layer.msg(result.data,{icon:1,time:1000},function () {
                            location.reload();
                        });
                    };
                },
                error: function () {
                    alert("异常！");
                }
            });
        })
    }
    function manualTrigger(ids) {
        $.ajax({
            type: "get",//方法类型
            dataType: "json",//预期服务器返回的数据类型
            url: "/admProjectAutoConfig/manualTrigger/"+ids,//url
            success: function (result) {
                if (result.code == 0) {
                    layer.msg(result.data,{icon:1,time:1000},function () {
                        location.reload();
                    });
                };
            },
            error: function () {
                alert("异常！");
            }
        });
    }

    function add() {
        layer.open({
            type: 2,
            title: '新增配置',
            area: ['500px', '500px'],
            fix: false, //
            closeBtn: true,
            shift: 2,
            shadeClose: false,
            content: ["add.html", 'no'],
            success: function (layero, index) {
                form.render();
            },
            yes: function () {
            }
        });
    }
    let dropData
    function update(data) {
        layer.open({
            type: 2,
            title: '修改配置',
            area: ['500px', '500px'],
            fix: false, //
            closeBtn: true,
            shift: 2,
            shadeClose: false,
            content: ["update.html", 'no'],
            success: function (layero, index) {
                const body = layer.getChildFrame('body', index);//获取弹出层的dom元素
                const iframeWin = layero.find('iframe')[0].contentWindow;
                body.find("#id").val(data.id);
                body.find("#projectId").val(data.projectId);
                body.find("#projectName").val(data.projectName);;
                body.find("#namespaceId").val(data.namespaceId);
                body.find("#namespaceName").val(data.namespaceName);
                body.find("#branch").val(data.branch);
                if (data.state==1) {
                    body.find("#state1").attr("checked", true);
                }else if(data.state==0){
                    body.find("#state0").attr("checked", true);
                }else if(data.state==2){
                    body.find("#state2").attr("checked", true);
                }
                iframeWin.layui.form.render();
            },
            yes: function () {
            }
        });
    }

    $('#query').click(function(){
        search();
    });
    $(document).keyup(function(event){
        if(event.keyCode ==13){
            search();
        }
    });
    function search(){
        const content = $('#content');
        //执行重载
        table.reloadData('admProjectAutoConfig', {
            method: 'get',
            page: {
                curr: 1 //重新从第 1 页开始
            }
            , where: {
                content: content.val(),
                projectId: $('#projectId').val(),
                namespaceId: $('#namespaceId').val(),
            }
        }, 'data');
    }


    $(function () {
        getProject("")
        getNamespace("")
    })
    projectNameInput = function(e){
        const val = $("#projectName").val();
        getProject(val)
    }
    let projectData
    function getProject(projectName) {
        $.ajax({
            type: "GET",//方法类型
            dataType: "json",//预期服务器返回的数据类型
            url: "/admProject/getAll?name="+projectName,//url
            success: function (result) {
                projectData = result
                $("#projectId").html("");
                var html = "";
                $("#projectId").html("<option value=\"\">请选择项目</option>");
                if (result != null) {
                    $.each(result, function (index, item) {
                        html += "<option  value='" + item.id + "'>" + item.projectName + "</option>";
                    })
                }
                $("#projectId").append(html);
                form.render('select');
                if (projectName != null && projectName !=''){
                    $(".projectId").find(".layui-form-select").addClass("layui-form-selected")
                }
            },
            error: function () {
                alert("异常！");
            }
        });
    }
    // 监听下拉框改变事件,修改输入框中的内容
    form.on("select(projectId)",function(data){
        let value=data.value
        let selectObj=projectData.filter(item=>{
            return item.id==value
        })
        $("#projectName").val(selectObj[0].projectName);
    })


    namespaceNameInput = function(e){
        const val = $("#namespaceName").val();
        getNamespace(val)
    }
    let namespaceData
    function getNamespace(name) {
        $.ajax({
            type: "GET",//方法类型
            dataType: "json",//预期服务器返回的数据类型
            url: "/admNamespace/getAll?name="+name,//url
            success: function (result) {
                namespaceData = result
                $("#namespaceId").html("");
                var html = "";
                $("#namespaceId").html("<option value=\"\">请选择命名空间</option>");
                if (result != null) {
                    $.each(result, function (index, item) {
                        html += "<option  value='" + item.id + "'>" + item.name + "</option>";
                    })
                }
                $("#namespaceId").append(html);
                form.render('select');
                if (name != null && name !=''){
                    $(".namespaceId").find(".layui-form-select").addClass("layui-form-selected")
                }
            },
            error: function () {
                alert("异常！");
            }
        });
    }
    // 监听下拉框改变事件,修改输入框中的内容
    form.on("select(namespaceId)",function(data){
        let value=data.value
        let selectObj=namespaceData.filter(item=>{
            return item.id==value
        })
        $("#namespaceName").val(selectObj[0].name);
    })





});
